/*
*@Author created by Wangbin
*@data Jan 22, 2018----2:52:07 PM
*/

package com.weizhong.update.impl;

import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.weizhong.update.model.AppOptimizeData;
import com.weizhong.update.model.CleanParameters;
import com.weizhong.update.util.Constances;
import com.weizhong.update.util.HttpTool;
import com.weizhong.update.util.JsonTool;

import android.app.WzOptimizeManager;
import android.app.util.LogUtil;
import android.content.Context;
import android.os.RemoteException;
import android.os.WZAccessServiceManager;
import android.os.WZBubbleUserInfo;
import android.text.TextUtils;

public class OptimizeManager {
	Context mContext = null;
	AppOptimizeData optimizeData = null;
	WzOptimizeManager wzOptimizeManager = null;
	public final static int REQUST_FAIL = -1;
	public OptimizeManager(Context context){
		mContext = context;
		wzOptimizeManager = (WzOptimizeManager) context.getSystemService("optimize");
		optimizeData = new AppOptimizeData();
	}

	public void printData(){
		if(optimizeData != null){
			LogUtil.d("optimizeData: " + optimizeData.toString());
		}
	}

	/**
	 * 更新优化数据
	 */
	public void updateOptimizeData(){
		new Thread(){
			public void run() {
				try {
					Thread.sleep(30 * 1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				while (true) {
					if(!initOptimizeServerValue()){
						LogUtil.d("OptimizeManager init fail");
						try {
							Thread.sleep(300 * 1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}else {
						printData();
						try {
							int sleepTime = optimizeData.getCleanParameters().getUpdateTime() * 60 * 1000; 
							LogUtil.d("OptimizeManager sleepTime : " + sleepTime);
							Thread.sleep(sleepTime);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}					
				}
			};
		}.start();
	}

	/**
	 * 重新请求服务器参数
	 * @return
	 */
	private boolean initOptimizeServerValue(){
		boolean result = true;
		try {
			WZBubbleUserInfo userInfo = WZAccessServiceManager.getBubbleUserFullInfo();

			NameValuePair bbCode = new BasicNameValuePair("bbCode",userInfo.getUserID());

			//性能开关
			int optimizeValue = getOptimizeControlValue(bbCode,Constances.OPTIMIZE_CONTROL_TYPE);
			if(optimizeValue < 0){
				result = false;
				LogUtil.d("getOptimizeControlValue OPTIMIZE_CONTROL_TYPE fail");
			}else{
				setOptimizeControl(optimizeValue);
				optimizeData.setServiceStatus(optimizeValue);
			}

			//吐司开关
			int toastValue = getOptimizeControlValue(bbCode,Constances.OPTIMIZE_TOAST_TYPE);
			if(toastValue < 0){
				result = false;
				LogUtil.d("getOptimizeControlValue OPTIMIZE_TOAST_TYPE fail");
			}else{
				setOptimizeToastControl(toastValue);
				optimizeData.setShowToast(toastValue);
			}
			
			//自启动开关
			int launchValue = getOptimizeControlValue(bbCode,Constances.OPTIMIZE_LAUNCH_TYPE);
			if(launchValue < 0){
				result = false;
				LogUtil.d("getOptimizeControlValue OPTIMIZE_LAUNCH_TYPE fail");
			}else{
				setOptimizeLaunchControl(launchValue);
				optimizeData.setLauchSwich(launchValue);
			}
			
			//自启动黑名单
			List<String> launchBlackList = getOptimizeListData(bbCode,Constances.OPTIMIZE_LAUNCH_BLACK_TYPE);
			if(launchBlackList == null){
				result = false;
				LogUtil.d("getOptimizeControlValue OPTIMIZE_LAUNCH_BLACK_TYPE fail");
			}else {
				setLaunchBlackList(launchBlackList);
				optimizeData.setAutoWorkBlackList(launchBlackList);
			}
			
			//自启动白名单
			List<String> launchList = getOptimizeListData(bbCode,Constances.OPTIMIZE_LAUNCH_WHITE_TYPE);
			if(launchList == null){
				result = false;
				LogUtil.d("getOptimizeControlValue OPTIMIZE_LAUNCH_WHITE_TYPE fail");
			}else {
				setLaunchWhiteList(launchList);
				optimizeData.setAutoWorkWhiteList(launchList);
			}
			
			//优化黑名单
			List<String> blackList = getOptimizeListData(bbCode,Constances.OPTIMIZE_BLACK_TYPE);
			if(blackList == null){
				result = false;
				LogUtil.d("getOptimizeControlValue OPTIMIZE_BLACK_TYPE fail");
			}else {
				setOptimizeBlackList(blackList);
				optimizeData.setBlackList(blackList);
			}
			
			//优化白名单
			List<String> whilteList = getOptimizeListData(bbCode,Constances.OPTIMIZE_WHITE_TYPE);
			if(whilteList == null){
				result = false;
				LogUtil.d("getOptimizeControlValue OPTIMIZE_WHITE_TYPE fail");
			}else {
				setOptimizeWhiteList(whilteList);
				optimizeData.setWhiteList(whilteList);
			}
			
			//清理参数
			CleanParameters cleanParameters = getCleanParameter(bbCode);
			if(cleanParameters == null){
				result = false;
				LogUtil.d("getOptimizeControlValue cleanParameters fail");
			}else {
				setCleanParameter(cleanParameters);
				optimizeData.setCleanParameters(cleanParameters);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取开关：0:关闭；1开启
	 * @param bbCode
	 * @param mType
	 * @return
	 */
	private int getOptimizeControlValue(NameValuePair bbCode,String mType){
		int result = REQUST_FAIL;
		String updateCheckUrl = Constances.optimize_check_url + Constances.optimize_switch_check_url;
		NameValuePair type = new BasicNameValuePair("type",mType);
		String jsonString = HttpTool.httpPostRequest(updateCheckUrl, bbCode, type);
		if (!TextUtils.isEmpty(jsonString)) {
			result = JsonTool.parseOptimizeSwitchData(jsonString);
		}
		return result;
	}
	
	/**
	 * 设置性能开关
	 * @param vaule
	 */
	public void setOptimizeControl(int vaule){
		if(wzOptimizeManager != null){
			try {
				wzOptimizeManager.setOptimizationControl(vaule);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 设置土司开关
	 * @param vaule
	 */
	public void setOptimizeToastControl(int vaule){
		if(wzOptimizeManager != null){
			try {
				wzOptimizeManager.setToastControl(vaule);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 设置自启动开关
	 * @param vaule
	 */
	public void setOptimizeLaunchControl(int vaule){
		if(wzOptimizeManager != null){
			try {
				wzOptimizeManager.setBootBroadcastControl(vaule);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取性能名单列表
	 * @param bbCode
	 * @param mType
	 * @return
	 */
	private List<String> getOptimizeListData(NameValuePair bbCode,String mType){
		List<String> lists = null;
		String updateCheckUrl = Constances.optimize_check_url + Constances.optimize_list_check_url;
		NameValuePair type = new BasicNameValuePair("type",mType);
		String jsonString = HttpTool.httpPostRequest(updateCheckUrl, bbCode, type);
		if (!TextUtils.isEmpty(jsonString)) {
			lists = JsonTool.parseOptimizeListData(jsonString);
		}
		return lists;
	}
	
	/**
	 * 设置性能优化白名单
	 * @param list
	 */
	public void setOptimizeWhiteList(List<String> list){
		if(wzOptimizeManager != null){
			try {
				if(list != null){
					Iterator<String> iterator = list.iterator();
					while(iterator.hasNext()){
						String temp = iterator.next();
						if(!wzOptimizeManager.isWhiteList(temp, 0)){
							wzOptimizeManager.addWhiteList(temp, 0);
						}
					}
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 设置性能优化黑名单
	 * @param list
	 */
	public void setOptimizeBlackList(List<String> list){
		if(wzOptimizeManager != null){
			try {
				if(list != null){
					Iterator<String> iterator = list.iterator();
					while(iterator.hasNext()){
						String temp = iterator.next();
						if(!wzOptimizeManager.isBlackList(temp, 0)){
							wzOptimizeManager.addBlackList(temp, 0);
						}
					}
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 设置性能自启动白名单
	 * @param list
	 */
	public void setLaunchWhiteList(List<String> list){
		if(wzOptimizeManager != null){
			try {
				if(list != null){
					Iterator<String> iterator = list.iterator();
					while(iterator.hasNext()){
						String temp = iterator.next();
						if(!wzOptimizeManager.isBootBroadcastWhiteList(temp, 0)){
							wzOptimizeManager.addBootBroadcastWhiteList(temp, 0);
						}
					}
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 设置性能自启动黑名单
	 * @param list
	 */
	public void setLaunchBlackList(List<String> list){
		if(wzOptimizeManager != null){
			try {
				if(list != null){
					Iterator<String> iterator = list.iterator();
					while(iterator.hasNext()){
						String temp = iterator.next();
						if(!wzOptimizeManager.isBootBroadcastBlackList(temp, 0)){
							wzOptimizeManager.addBootBroadcastBlackList(temp, 0);
						}
					}
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取优化参数
	 * @param bbCode
	 * @return
	 */
	private CleanParameters getCleanParameter(NameValuePair bbCode){
		CleanParameters cleanParameters = null;
		String updateCheckUrl = Constances.optimize_check_url + Constances.optimize_para_check_url;
		String jsonString = HttpTool.httpPostRequest(updateCheckUrl, bbCode);
		if (!TextUtils.isEmpty(jsonString)) {
			cleanParameters = JsonTool.parseOptimizeParameters(jsonString);
		}
		return cleanParameters;
	}
	
	/**
	 * 设置清理参数
	 * @param cleanParameters
	 */
	public void setCleanParameter(CleanParameters cleanParameters) {
		try {
			wzOptimizeManager.setKillRecentAppTime(cleanParameters.getTaskNums());
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}